# -*- coding: utf-8 -*-
import json
import os
from time import sleep

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QDockWidget, QAction, QFileDialog
import cv2
import numpy as np
import copy
from imageManager import *

PARA_PATH = os.path.dirname(__file__)


def calcAndDrawHist(image, color):
    hist = cv2.calcHist([image], [0], None, [256], [0.0, 255.0])
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)
    print(maxVal, minVal, maxLoc, minLoc)
    histImg = np.zeros([256, 256, 3], np.uint8)
    hpt = int(0.9 * 256)

    for h in range(256):
        intensity = int(hist[h] * hpt / maxVal)
        cv2.line(histImg, (h, 256), (h, 256 - intensity), color)

    return histImg


class binGui(QtWidgets.QWidget):
    update_para_signal = QtCore.pyqtSignal(int, dict)
    para = dict()
    index = 0

    def __init__(self, parent=None):
        super(binGui, self).__init__(parent)
        self.imgMat = None

    def initPara(self):
        parafile = os.path.join(PARA_PATH, "module_para.json")
        with open(parafile, "r", encoding='utf-8') as f:
            self.para = json.loads(f.read())

    def setPara(self, index, para):
        self.index = index
        if para is None:
            return
        if para["version"] == self.para["version"]:
            self.para = para

        self.spinbox_theshold.setValue(self.para["value"])
        self.threshold_proc(self.para["value"])

    def initUI(self):
        self.initPara()
        self.imgMat = copy.deepcopy(img_mng.img)
        self.histLabel = QtWidgets.QLabel(self)
        # self.histLabel.setFixedSize(200, 200)

        self.thrsSplider = QtWidgets.QSlider(self)
        self.thrsSplider.setRange(1, 255)
        self.thrsSplider.setSingleStep(1)
        self.thrsSplider.setOrientation(1)
        self.thrsSplider.setTickPosition(QtWidgets.QSlider.TicksBelow)
        self.thrsSplider.setTickInterval(5)

        self.spinbox_theshold = QtWidgets.QSpinBox(self)
        self.spinbox_theshold.setMaximum(255)
        self.spinbox_theshold.setSingleStep(1)
        self.spinbox_theshold.valueChanged.connect(self.threshold_changed)
        hbox1 = QtWidgets.QHBoxLayout()
        hbox1.addWidget(self.thrsSplider)
        hbox1.addWidget(self.spinbox_theshold)

        btn_calc = QtWidgets.QPushButton(self)
        btn_calc.setText("calc")

        btn_ok = QtWidgets.QPushButton(self)
        btn_ok.setText("ok")
        btn_ok.clicked.connect(self.btn_ok_clicked)

        btn_cancel = QtWidgets.QPushButton(self)
        btn_cancel.setText("cancel")
        btn_cancel.clicked.connect(self.btn_cancel_clicked)
        hbox3 = QtWidgets.QHBoxLayout()
        hbox3.addWidget(btn_ok)
        hbox3.addWidget(btn_cancel)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.histLabel)
        vlayout.addLayout(hbox1)
        vlayout.addWidget(btn_calc)
        vlayout.addLayout(hbox3)

        btn_calc.clicked.connect(self.btn_calc_clicked)
        self.thrsSplider.valueChanged.connect(self.changeThresValue)

    def threshold_proc(self, val):
        if self.imgMat is None:
            return
        if len(self.imgMat.shape) == 3:
            self.imgMat = cv2.cvtColor(self.imgMat, cv2.COLOR_RGB2GRAY)
        ret, thresh = cv2.threshold(self.imgMat, val, 255, 0)

        img_mng.dispImg(thresh)
        img_mng.img = thresh

    def threshold_changed(self):
        value = self.spinbox_theshold.value()
        self.thrsSplider.setValue(value)
        self.threshold_proc(value)

    def changeThresValue(self):
        value = self.thrsSplider.value()
        self.spinbox_theshold.setValue(value)
        self.threshold_proc(value)

    def btn_calc_clicked(self):
        self.imgMat = copy.deepcopy(img_mng.img)
        if self.imgMat is None:
            return
        if len(self.imgMat.shape) == 3:
            b, g, r = cv2.split(self.imgMat)
            hisimg = calcAndDrawHist(g, [255, 0, 0])
            h = (int(self.histLabel.width()) + 3) // 4
            w = (int(self.histLabel.height()) + 3) // 4
            size = (4 * w, 4 * h)
            shrink = cv2.resize(hisimg, size, interpolation=cv2.INTER_AREA)
            # cv2.imshow('img', shrink)
            shrink = cv2.cvtColor(shrink, cv2.COLOR_BGR2RGB)
            QtImg = QtGui.QImage(shrink.data,
                                 shrink.shape[1],
                                 shrink.shape[0],
                                 QtGui.QImage.Format_RGB888)
            self.histLabel.setPixmap(QtGui.QPixmap.fromImage(QtImg))
        else:
            hisimg = calcAndDrawHist(self.imgMat, [255, 0, 0])

            h = (int(self.histLabel.width()) + 3) // 4
            w = (int(self.histLabel.height()) + 3) // 4
            size = (4 * w, 4 * h)
            shrink = cv2.resize(hisimg, size, interpolation=cv2.INTER_AREA)
            # cv2.imshow('img', shrink)
            shrink = cv2.cvtColor(shrink, cv2.COLOR_BGR2RGB)
            QtImg = QtGui.QImage(shrink.data,
                                 shrink.shape[1],
                                 shrink.shape[0],
                                 QtGui.QImage.Format_RGB888)
            self.histLabel.setPixmap(QtGui.QPixmap.fromImage(QtImg))

    def btn_ok_clicked(self):
        self.para["value"] = self.spinbox_theshold.value()
        self.update_para_signal.emit(self.index, self.para)

    def btn_cancel_clicked(self):
        self.close()

    def run(self, para):
        value = para["value"]
        img = img_mng.img
        if img is None:
            return
        ret, thresh = cv2.threshold(img, value, 255, 0)
        img_mng.img = thresh
        img_mng.dispImg(thresh)



if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ui = binGui()
    ui.initUI()
    ui.show()
    sys.exit(app.exec_())
